package com.forehope.portal.aslpUtil;

import com.actionsoft.bpms.bo.engine.BO;
import com.actionsoft.bpms.bpmn.constant.ProcessRuntimeConst;
import com.actionsoft.bpms.bpmn.engine.cache.ProcessDefCache;
import com.actionsoft.bpms.bpmn.engine.model.def.ProcessDefinition;
import com.actionsoft.bpms.bpmn.engine.model.def.UserTaskModel;
import com.actionsoft.bpms.bpmn.engine.model.run.delegate.EAITaskInstance;
import com.actionsoft.bpms.bpmn.engine.model.run.delegate.ProcessInstance;
import com.actionsoft.bpms.bpmn.engine.model.run.delegate.TaskInstance;
import com.actionsoft.bpms.commons.database.RowMap;
import com.actionsoft.bpms.commons.mvc.view.ResponseObject;
import com.actionsoft.bpms.commons.security.ac.AccessControlAPI;
import com.actionsoft.bpms.commons.security.ac.model.NavFunctionACCM;
import com.actionsoft.bpms.commons.security.basic.Query1Model;
import com.actionsoft.bpms.commons.security.basic.cache.PermissionListCache;
import com.actionsoft.bpms.commons.security.basic.model.PermissionAssnModel;
import com.actionsoft.bpms.commons.security.basic.model.PermissionListModel;
import com.actionsoft.bpms.org.cache.UserCache;
import com.actionsoft.bpms.org.cache.UserMapCache;
import com.actionsoft.bpms.org.model.UserMapModel;
import com.actionsoft.bpms.org.model.UserModel;
import com.actionsoft.bpms.schedule.system.SYS_HttpExecute;
import com.actionsoft.bpms.server.RequestParams;
import com.actionsoft.bpms.server.UserContext;
import com.actionsoft.bpms.util.DBSql;
import com.actionsoft.sdk.local.SDK;
import com.actionsoft.sdk.local.api.*;
import com.actionsoft.sdk.service.TaskApi;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import javafx.concurrent.Task;
import jodd.util.StringUtil;
import org.apache.commons.collections.ListUtils;
import org.apache.commons.lang.StringUtils;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Time;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class ProcessUtil {
    /**
     * 处理数据
     */
    public Map<String, Object> dueData(UserContext userContext, RequestParams requestParams, List<JSONObject> listData, String type) {
        Map<String, Object> resultMap = new HashMap<>();
        /**
         * 处理数据
         */
        String queryData = requestParams.get("query");
        JSONObject query = JSONObject.parseObject(queryData);
        int nowPage = query.getInteger("nowPage");
        int pageNum = query.getInteger("pageNum");
        //查询字段
        JSONObject fieldJSON = query.getJSONObject("fieldQuery");
        //排序字段
        JSONObject orderJSON = query.getJSONObject("order");

        List<JSONObject> resultList = new ArrayList<>();
        //处理排序
        String[] orderToDoFileds = {"processTitle", "processType", "owerName", "arravieTime"};
        String[] orderTrackFileds = {"processTitle", "processType", "processCreateUser", "processState", "trackTime"};
        String[] myCreateFileds = {"processTitle", "processType", "targetUser", "processState", "processCreateData"};
        if ("todo".equals(type)) {
            Timestamp nowTime = new Timestamp(System.currentTimeMillis());
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            //处理查询
            List<TaskInstance> list = SDK.getTaskQueryAPI().eaiTask().target(userContext.getUID()).list();


            for (TaskInstance taskInstance : list) {
                JSONObject jsonObjectNew = new JSONObject();
                String taskInstId = taskInstance.getId();
                //流程标题
                jsonObjectNew.put("processTitle", taskInstance.getTitle());
                //来自
                jsonObjectNew.put("owerName", taskInstance.getOwner());
                //流程版本ID
                jsonObjectNew.put("processDefId", taskInstance.getProcessDefId());
                //表单打开url
                /*******************--------------处理EAI任务打开链接-----------------------********************/
                // 调用App
                String sourceAppId = "com.awspaas.user.apps.eai";
                // aslp服务地址
                String aslp = "aslp://com.awspaas.user.apps.eai/GetKdToDoList";
                // 参数定义列表
                Map params = new HashMap<String, Object>();
                //办理人用户账号,必填
                params.put("uid", userContext.getUID());
                //链接URL,必填
                params.put("url", taskInstance.getExt3());
                System.out.println("---------------taskInstance.getExt3():"+taskInstance.getExt3());
                params.put("type", "费控");
                AppAPI appAPI = SDK.getAppAPI();
                //获取金蝶待办数据
                ResponseObject ro = appAPI.callASLP(appAPI.getAppContext(sourceAppId), aslp, params);
                if (ro.isOk()) {
                    System.out.println("---------------------ro.getData:"+JSONObject.toJSONString(ro.getData()));
                    jsonObjectNew.put("openUrl",String.valueOf(ro.getData()));
                }else{
                    //TODO 后续可优化成报错页面
                    jsonObjectNew.put("openUrl","/");
                }
                //流程类型
                jsonObjectNew.put("processType", "EAI任务");
                //流程实例id
                jsonObjectNew.put("processInstId", taskInstance.getProcessInstId());

                jsonObjectNew.put("taskInstId", taskInstId);
                //获取任务实例
                String owner = taskInstance.getOwner();
                jsonObjectNew.put("fromUser", owner);
                UserModel userModel = SDK.getORGAPI().getUser(owner);
                if (userModel != null) {
                    jsonObjectNew.put("fromUser", userModel.getUserName());
                }
                Timestamp beginTime = taskInstance.getBeginTime();

                //任务创建时间
                jsonObjectNew.put("arravieTime", simpleDateFormat.format(beginTime));//创建时间

                //获取超时时间
                Timestamp dueTime = taskInstance.getDueTime();
                //获取优先级  0:低，1：普通，2：中，3：高
                int priority = taskInstance.getPriority();
                Boolean isRead = taskInstance.getReadState()==1?true:false;
                jsonObjectNew.put("isRead", isRead);
                //任务是否紧急
                if (3 == priority) {
                    jsonObjectNew.put("isImportant", true);
                } else {
                    jsonObjectNew.put("isImportant", false);
                }
                if (dueTime == null) {
                    //不会超期，显示停留时间
                    jsonObjectNew.put("dataInfo", getTime(beginTime, nowTime, "已停留"));
                    jsonObjectNew.put("isYq", false);
                } else {
                    if (nowTime.getTime() > dueTime.getTime()) {
                        //超期
                        jsonObjectNew.put("dataInfo", getTime(dueTime, nowTime, "已逾期"));
                        jsonObjectNew.put("isYq", true);
                    } else {
                        jsonObjectNew.put("dataInfo", getTime(beginTime, nowTime, "已停留"));
                        jsonObjectNew.put("isYq", false);
                    }
                }
                listData.add(jsonObjectNew);
            }
            resultList = this.filterToDoData(fieldJSON, listData);
            resultMap.put("totalNum", resultList.size());
            this.orderUtil(orderJSON, resultList, orderToDoFileds);
        }
        if ("track".equals(type)) {
            //处理查询
            resultList = this.filterTrackData(fieldJSON, listData);
            resultMap.put("totalNum", resultList.size());
            this.orderUtil(orderJSON, resultList, orderTrackFileds);
        }
        if ("mycreate".equals(type)) { //处理查询
            resultList = this.filterMyCreateData(fieldJSON, listData);
            resultMap.put("totalNum", resultList.size());
            this.orderUtil(orderJSON, resultList, myCreateFileds);
        }
        //处理分页
        List<JSONObject> list = resultList;
        if (resultList != null && resultList.size() > 0) {
            list = this.subList(resultList, pageNum, nowPage);
        }
        resultMap.put("resultData", list);
        return resultMap;
    }

    /**
     * 分页
     */
    public List<JSONObject> subList(List<JSONObject> list, int pageSize, int pageNum) {
        int count = list.size();
        int pages = count % pageSize == 0 ? count / pageSize : count / pageSize + 1;
        int start = pageNum <= 0 ? 0 : (pageNum > pages ? (pages - 1) * pageSize : (pageNum - 1) * pageSize);
        int end = pageSize;
        return list.stream().skip(start).limit(pageSize).collect(Collectors.toList());
    }


    /**
     * 排序
     */
    public void orderUtil(JSONObject orderJSON, List<JSONObject> resultList, String[] fileds) {
        /**
         * 处理排序数据
         */
        List<String> sortProperties = new ArrayList<>();
        //动态指定要排序的属性字段
        Map<String, Boolean> sortOrders = new HashMap<>();
        //动态指定属性字段对应的排序顺序（true表示降序，false表示升序）
        for (String filed : fileds) {
            String orderQuery = orderJSON.getString(filed);
            if (StringUtil.isNotEmpty(orderQuery)) {
                sortProperties.add(filed);
                if ("asc".equals(orderQuery)) {
                    sortOrders.put(filed, true);
                } else {
                    sortOrders.put(filed, false);
                }
            }
        }

        if (sortProperties != null && sortProperties.size() > 0 && sortOrders != null && sortOrders.size() > 0) {
            // 构建Comparator链
            Comparator<JSONObject> comparator = null;
            for (int i = 0; i < sortProperties.size(); i++) {
                final int propertyIndex = i;
                Comparator<JSONObject> propertyComparator = Comparator.nullsLast(Comparator.comparing(
                        (JSONObject o) -> o.getString(sortProperties.get(propertyIndex)),
                        String.CASE_INSENSITIVE_ORDER
                ));

                if (sortOrders.get(sortProperties.get(propertyIndex))) {
                    propertyComparator = Comparator.nullsLast(propertyComparator.reversed());
                }

                if (comparator == null) {
                    comparator = propertyComparator;
                } else {
                    comparator = comparator.thenComparing(propertyComparator);
                }
            }
            Collections.sort(resultList, comparator);
        }
    }


    /**
     * 待办筛选查询
     */

    public List<JSONObject> filterToDoData(JSONObject fieldJSON, List<JSONObject> list) {
        /**
         * 处理二级查询数据
         */
        String processTitle = fieldJSON.getString("processTitle");
        String processType = fieldJSON.getString("processType");
        String owerName = fieldJSON.getString("owerName");
        boolean isYq = fieldJSON.getBoolean("isYq");
        String releaseTime = fieldJSON.getString("releaseTime");
        /**
         * 处理三级查询数据（发布时间）
         */
        JSONObject releaseTimeJSON = JSONObject.parseObject(releaseTime);
        String beginTime = releaseTimeJSON.getString("beginTime");
        String endTime = releaseTimeJSON.getString("endTime");
        /**
         * 处理查询数据
         */
        Stream<JSONObject> queryResult = list.stream().filter(jsonObject -> jsonObject.getString("processTitle").contains(processTitle)
                && jsonObject.getString("processType").contains(processType)
                && (StringUtil.isEmpty(jsonObject.getString("owerName")) ? "1".equals("1") : jsonObject.getString("owerName").contains(owerName))
        );
        List<JSONObject> resultList = queryResult
                .sorted(Comparator.comparing((JSONObject obj) -> obj.getString("arravieTime"), Comparator.nullsLast(String::compareTo)).reversed())
                .collect(Collectors.toList());
        //处理排序
        if (isYq == true) {
            resultList = resultList.stream().filter(jsonObject -> jsonObject.getBoolean("isYq") == isYq).collect(Collectors.toList());
        }
        return resultList;
    }


    /**
     * 已办筛选查询
     */

    public List<JSONObject> filterTrackData(JSONObject fieldJSON, List<JSONObject> list) {
        /**
         * 处理二级查询数据
         */
        String processTitle = fieldJSON.getString("processTitle");
        String processType = fieldJSON.getString("processType");
        String processCreateUser = fieldJSON.getString("processCreateUser");
        String processState = fieldJSON.getString("processState");
        String releaseTime = fieldJSON.getString("releaseTime");
        /**
         * 处理三级查询数据（发布时间）
         */
        JSONObject releaseTimeJSON = JSONObject.parseObject(releaseTime);
        String beginTime = releaseTimeJSON.getString("beginTime");
        String endTime = releaseTimeJSON.getString("endTime");
        /**
         * 处理查询数据
         */
        System.out.println("------------------:" + JSONObject.toJSONString(list));
        Stream<JSONObject> queryResult = list.stream().filter(jsonObject -> jsonObject.getString("processTitle").contains(processTitle)
                && jsonObject.getString("processType").contains(processType)
                && (StringUtil.isEmpty(jsonObject.getString("processCreateUser")) ? "1".equals("1") : jsonObject.getString("processCreateUser").contains(processCreateUser))
                && StringUtil.isEmpty(jsonObject.getString("processState")) ? "1".equals("1") : jsonObject.getString("processState").contains(processState)
        );
        List<JSONObject> resultList = queryResult.collect(Collectors.toList());
        return resultList;
    }

    /**
     * 发起筛选查询
     */

    public List<JSONObject> filterMyCreateData(JSONObject fieldJSON, List<JSONObject> list) {
        /**
         * 处理二级查询数据
         */
        String processTitle = fieldJSON.getString("processTitle");
        String processType = fieldJSON.getString("processType");
        String processCreateUser = fieldJSON.getString("targetUser");
        String processState = fieldJSON.getString("processState");
        String releaseTime = fieldJSON.getString("releaseTime");
        /**
         * 处理三级查询数据（发布时间）
         */
        JSONObject releaseTimeJSON = JSONObject.parseObject(releaseTime);
        String beginTime = releaseTimeJSON.getString("beginTime");
        String endTime = releaseTimeJSON.getString("endTime");
        /**
         * 处理查询数据
         */
        Stream<JSONObject> queryResult = list.stream().filter(jsonObject -> jsonObject.getString("processTitle").contains(processTitle)
                && jsonObject.getString("processType").contains(processType)
                && (StringUtil.isEmpty(jsonObject.getString("targetUser")) ? "1".equals("1") : jsonObject.getString("targetUser").contains(processCreateUser))
                && jsonObject.getString("processState").contains(processState)
        );
        List<JSONObject> resultList = queryResult.collect(Collectors.toList());
        return resultList;
    }

    public String getTime(Timestamp beginTime, Timestamp operaTime, String type) {
        // 计算时间差（以毫秒为单位）
        long milliseconds = operaTime.getTime() - beginTime.getTime();
        // 将毫秒转换为天、小时、分钟和秒
        long seconds = milliseconds / 1000;
        long days = seconds / (24 * 3600);
        seconds = seconds % (24 * 3600);
        long hours = seconds / 3600;
        seconds = seconds % 3600;
        long minutes = seconds / 60;
        seconds = seconds % 60;
        String result = type;
        if (days > 0) {
            result = result + days + "天";
        }
        if (hours > 0) {
            result = result + hours + "小时";
        }
        if (minutes > 0 && days == 0) {
            result = result + minutes + "分";
        }
        if (days == 0 && hours == 0) {
            result = result + seconds + "秒";
        }
        return result;
    }

    public List<JSONObject> getTodoList(UserContext userContext) {
        //查询条数
        String sqlCount = "select count(ID) as count from wfc_task where target = '" + userContext.getUID() + "'";
        int num = DBSql.getInt(sqlCount, "count");

        List<JSONObject> jsonArrayResult = new ArrayList<>();
        // 调用App
        String sourceAppId = "com.actionsoft.apps.workbench";
        // aslp服务地址
        String aslp = "aslp://com.actionsoft.apps.workbench/TodoTask";
        // 参数定义列表
        Map params = new HashMap<String, Object>();
        //搜索条件：任务来自,值为用户UID,多个以逗号隔开,非必填
//        params.put("owner", owner);
        //查询数据的起始条数,必填
        params.put("start", 0);
        //每页显示多少条,必填
        params.put("limit", num);
        //搜索条件：时间区间之结束时间,非必填
//        params.put("end", end);
        //用于查询特定流程组定义的实例数据，多个使用英文半角逗号分隔,非必填
//        params.put("processGroupIds", processGroupIds);
        //搜索条件：任务标题,非必填
//        params.put("title", title);
        //搜索条件：时间区间之开始时间,非必填
//        params.put("begin", begin);
        //会话ID,必填

        params.put("sid", userContext.getSessionId());
        AppAPI appAPI = SDK.getAppAPI();
        //工作台待办任务列表
        ResponseObject ro = appAPI.callASLP(appAPI.getAppContext(sourceAppId), aslp, params);
        ProcessDefCache processDefCache = ProcessDefCache.getInstance();

        if (ro.isOk()) {
            Map map = ro.getData(Map.class);
            if (map != null) {
                Timestamp nowTime = new Timestamp(System.currentTimeMillis());
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String taskList = String.valueOf(map.get("taskList"));
                JSONArray jsonArray = JSONArray.parseArray(taskList);
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    JSONObject jsonObjectNew = new JSONObject();
                    String taskInstId = jsonObject.getString("taskInstId");
                    //流程标题
                    jsonObjectNew.put("processTitle", jsonObject.getString("title"));
                    //来自
                    jsonObjectNew.put("owerName", jsonObject.getString("owerName"));
                    //流程版本ID
                    jsonObjectNew.put("processDefId", jsonObject.getString("processDefId"));
                    //表单打开url
                    jsonObjectNew.put("openUrl", jsonObject.getString("url"));
                    //获取流程定义
                    ProcessDefinition processDefinition = processDefCache.get(jsonObject.getString("processDefId"));
                    if (processDefinition != null) {
                        String name = processDefinition.getName();
                        //流程类型
                        jsonObjectNew.put("processType", name);
                        //流程实例id
                        jsonObjectNew.put("processInstId", jsonObject.getString("processInstId"));

                        jsonObjectNew.put("taskInstId", taskInstId);
                        //获取任务实例
                        TaskInstance taskInstance = SDK.getTaskAPI().getInstanceById(taskInstId);
                        String owner = taskInstance.getOwner();
                        jsonObjectNew.put("fromUser", owner);
                        UserModel userModel = SDK.getORGAPI().getUser(owner);
                        if (userModel != null) {
                            jsonObjectNew.put("fromUser", userModel.getUserName());
                        }
                        Timestamp beginTime = taskInstance.getBeginTime();

                        //任务创建时间
                        jsonObjectNew.put("arravieTime", simpleDateFormat.format(beginTime));//创建时间

                        //获取超时时间
                        Timestamp dueTime = taskInstance.getDueTime();
                        //获取优先级  0:低，1：普通，2：中，3：高
                        int priority = taskInstance.getPriority();
                        Boolean isRead = jsonObject.getBoolean("isRead");
                        jsonObjectNew.put("isRead", isRead);
                        //任务是否紧急
                        if (3 == priority) {
                            jsonObjectNew.put("isImportant", true);
                        } else {
                            jsonObjectNew.put("isImportant", false);
                        }
                        if (dueTime == null) {
                            //不会超期，显示停留时间
                            jsonObjectNew.put("dataInfo", getTime(beginTime, nowTime, "已停留"));
                            jsonObjectNew.put("isYq", false);
                        } else {
                            if (nowTime.getTime() > dueTime.getTime()) {
                                //超期
                                jsonObjectNew.put("dataInfo", getTime(dueTime, nowTime, "已逾期"));
                                jsonObjectNew.put("isYq", true);
                            } else {
                                jsonObjectNew.put("dataInfo", getTime(beginTime, nowTime, "已停留"));
                                jsonObjectNew.put("isYq", false);
                            }
                        }
                        jsonArrayResult.add(jsonObjectNew);
                    }
                }
            }
        }
        return jsonArrayResult;
    }


    /**
     * 已办任务
     *
     * @param userContext
     * @return
     */
    public List<JSONObject> getTrackList(UserContext userContext, RequestParams requestParams) {
        String queryData = requestParams.get("query");
        JSONObject query = JSONObject.parseObject(queryData);
        int nowPage = query.getInteger("nowPage");
        int pageNum = query.getInteger("pageNum");
        //查询字段
        JSONObject fieldJSON = query.getJSONObject("fieldQuery");
        List<JSONObject> jsonArrayResult = new ArrayList<>();
        // 调用App
        String sourceAppId = "com.actionsoft.apps.workbench";
        // aslp服务地址
        String aslp = "aslp://com.actionsoft.apps.workbench/HistoryTaskASLP";
        // 参数定义列表
        Map params = new HashMap<String, Object>();
        //查询数据的起始条数,必填
        params.put("start", ((nowPage - 1) * pageNum));
        //每页显示多少条,必填
        params.put("limit", pageNum);
        //会话ID,必填
        params.put("sid", userContext.getSessionId());
        AppAPI appAPI = SDK.getAppAPI();
        //工作台待办任务列表
        ResponseObject ro = appAPI.callASLP(appAPI.getAppContext(sourceAppId), aslp, params);
        ProcessDefCache processDefCache = ProcessDefCache.getInstance();
        if (ro.isOk()) {
            Map map = ro.getData(Map.class);
            if (map != null) {
                String sql = "select * from wfc_process where STARTACTIVITYID!=''";
                Set<String> processInst = new HashSet<>();
                String resultSql = "";
                String taskList = String.valueOf(map.get("taskList"));
                JSONArray jsonArray = JSONArray.parseArray(taskList);

                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    String processInstId = jsonObject.getString("processInstId");
                    processInst.add(processInstId);
                }

                for (String process : processInst) {
                    resultSql = resultSql + "'" + process + "'" + ",";
                }
                if (StringUtil.isNotEmpty(resultSql)) {
                    resultSql = resultSql.substring(0, resultSql.length() - 1);
                    sql = sql + "and ID in (" + resultSql + ")";
                }

                List<RowMap> maps = DBSql.getMaps(sql);
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject jsonObject = jsonArray.getJSONObject(i);

                    JSONObject jsonObjectNew = new JSONObject();
                    String taskInstId = jsonObject.getString("taskInstId");
                    //流程标题
                    jsonObjectNew.put("processTitle", jsonObject.getString("processTitle"));
                    //流程版本ID
                    jsonObjectNew.put("processDefId", jsonObject.getString("processDefId"));//流程定义id
                    //流程标题
                    jsonObjectNew.put("openUrl", jsonObject.getString("url"));
                    //获取流程定义
                    ProcessDefinition processDefinition = processDefCache.get(jsonObject.getString("processDefId"));
                    if (processDefinition != null) {
                        String name = processDefinition.getName();
                        //流程类型
                        jsonObjectNew.put("processType", name);
                        String processInstId = jsonObject.getString("processInstId");
                        jsonObjectNew.put("processInstId", processInstId);//流程实例id
                        //流程状态
                        ProcessInstance processInstance = SDK.getProcessAPI().getInstanceById(processInstId);
                        String controlState = processInstance.getControlState();
                        switch (controlState) {
                            case ProcessRuntimeConst.INST_STATE_ACTIVE:
                                jsonObjectNew.put("processState", "审批中");
                                break;
                            case ProcessRuntimeConst.INST_STATE_CANCEL:
                                jsonObjectNew.put("processState", "已取消");
                                break;
                            case ProcessRuntimeConst.INST_STATE_END:
                                jsonObjectNew.put("processState", "已完成");
                                break;
                            case ProcessRuntimeConst.INST_STATE_SUSPEND:
                                jsonObjectNew.put("processState", "已挂起");
                                break;
                            case ProcessRuntimeConst.INST_STATE_TERMINATE:
                                jsonObjectNew.put("processState", "已终止");
                                break;
                            default:
                                jsonObjectNew.put("processState", "状态异常");
                                break;
                        }
                        //流程创建人
                        String createUser = processInstance.getCreateUser();
                        if (StringUtils.isNotEmpty(createUser)) {
                            UserModel userModel = UserCache.getModel(createUser);
                            if (userModel != null) {
                                jsonObjectNew.put("processCreateUser", userModel.getUserName());
                            } else {
                                jsonObjectNew.put("processCreateUser", createUser);
                            }
                        } else {
                            //判断节点类型，如果是callActivity,则表示有子流程正在办理,寻找子流程办理人
                            jsonObjectNew.put("processCreateUser", "人员已被删除");
                        }
                        jsonObjectNew.put("taskInstId", taskInstId);
                        //获取任务实例
                        String endTime = jsonObject.getString("endTime");
                        if (StringUtil.isNotEmpty(endTime)) {
                            String endArr[] = endTime.split(" ");
                            String end = endArr[0];
                            //任务创建时间
                            jsonObjectNew.put("trackTime", end);//创建时间
                        }

                        Boolean isRead = jsonObject.getBoolean("isRead");
                        jsonObjectNew.put("isRead", isRead);
                        jsonArrayResult.add(jsonObjectNew);
                    }
                }
            }
        }
        return jsonArrayResult;
    }


    /**
     * 已办任务
     *
     * @param userContext
     * @return
     */
    public int getTaskNum(UserContext userContext) {
        String sourceAppId = "com.actionsoft.apps.workbench";
        // aslp服务地址
        String aslp = "aslp://com.actionsoft.apps.workbench/TypeTaskCountByUserASLP";
        Map params = new HashMap<String, Object>();
        params.put("type", "history");
        params.put("sid", userContext.getSessionId());
        AppAPI appAPI = SDK.getAppAPI();
        //工作台待办任务列表
        ResponseObject ro = appAPI.callASLP(appAPI.getAppContext(sourceAppId), aslp, params);
        if (ro.isOk()) {
            Map map = ro.getData(Map.class);
            return Integer.valueOf(map.get("count").toString());
        }
        return 0;
    }

    /**
     * 我的发起
     *
     * @param userContext
     * @return
     */
    public List<JSONObject> getMyCreateList(UserContext userContext) {
        List<JSONObject> jsonArrayResult = new ArrayList<>();
        //查询条数
        String sqlCount = "select count(ID) as count from wfc_process where CREATEUSER = '" + userContext.getUID() + "'";
        int num = DBSql.getInt(sqlCount, "count");
        // 调用App
        String sourceAppId = "com.actionsoft.apps.workbench";
        // aslp服务地址
        String aslp = "aslp://com.actionsoft.apps.workbench/TrackTaskASLP";
        // 参数定义列表
        Map params = new HashMap<String, Object>();
        //搜索条件：任务来自,值为用户UID,多个以逗号隔开,非必填
//        params.put("owner", owner);
        //查询数据的起始条数,必填
        params.put("start", 0);
        //每页显示多少条,必填
        params.put("limit", num);
        //搜索条件：时间区间之结束时间,非必填
//        params.put("end", end);
        //用于查询特定流程组定义的实例数据，多个使用英文半角逗号分隔,非必填
//        params.put("processGroupIds", processGroupIds);
        //搜索条件：任务标题,非必填
//        params.put("title", title);
        //搜索条件：时间区间之开始时间,非必填
//        params.put("begin", begin);
        //会话ID,必填
        params.put("sid", userContext.getSessionId());
        AppAPI appAPI = SDK.getAppAPI();
        //工作台待办任务列表
        ResponseObject ro = appAPI.callASLP(appAPI.getAppContext(sourceAppId), aslp, params);
        ProcessDefCache processDefCache = ProcessDefCache.getInstance();

        if (ro.isOk()) {
            Map map = ro.getData(Map.class);
            if (map != null) {
                /**
                 * 处理当前办理人
                 */
                Connection conn = null;
                try {
                    String sql = "select PROCESSINSTID,ID from wfc_task where TASKSTATE!='2' and TASKSTATE!='9'";
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                    SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Set<String> processInst = new HashSet<>();
                    String resultSql = "";


                    Timestamp nowTime = new Timestamp(System.currentTimeMillis());
                    String taskList = String.valueOf(map.get("taskList"));
                    JSONArray jsonArray = JSONArray.parseArray(taskList);

                    for (int i = 0; i < jsonArray.size(); i++) {
                        JSONObject jsonObject = jsonArray.getJSONObject(i);
                        String processInstId = jsonObject.getString("id");
                        ProcessInstance processInstance = SDK.getProcessAPI().getInstanceById(processInstId);
                        //流程状态
                        String controlState = processInstance.getControlState();
                        if (ProcessRuntimeConst.INST_STATE_ACTIVE.equals(controlState)) {
                            processInst.add(processInstId);
                        }
                    }

                    for (String process : processInst) {
                        resultSql = resultSql + "'" + process + "'" + ",";
                    }
                    if (StringUtil.isNotEmpty(resultSql)) {
                        resultSql = resultSql.substring(0, resultSql.length() - 1);
                        sql = sql + "and PROCESSINSTID in (" + resultSql + ")";
                    }
                    conn = DBSql.open();
                    List<RowMap> maps = DBSql.getMaps(conn, sql);

                    for (int i = 0; i < jsonArray.size(); i++) {
                        JSONObject jsonObject = jsonArray.getJSONObject(i);
                        JSONObject jsonObjectNew = new JSONObject();
                        //流程标题
                        jsonObjectNew.put("processTitle", jsonObject.getString("processTitle"));
                        //流程版本ID
                        jsonObjectNew.put("processDefId", jsonObject.getString("processDefId"));
                        //表单打开url
                        jsonObjectNew.put("openUrl", jsonObject.getString("url"));
                        //获取流程定义
                        ProcessDefinition processDefinition = processDefCache.get(jsonObject.getString("processDefId"));
                        if (processDefinition != null) {
                            String name = processDefinition.getName();
                            //流程类型
                            jsonObjectNew.put("processType", name);
                            //流程实例id
                            String processInstId = jsonObject.getString("id");
                            jsonObjectNew.put("processInstId", processInstId);
                            ProcessInstance processInstance = SDK.getProcessAPI().getInstanceById(processInstId);
                            Timestamp timestamp = processInstance.getCreateTime();
                            String processCreateData = simpleDateFormat.format(timestamp);
                            jsonObjectNew.put("processCreateData", processCreateData);


                            //流程状态
                            String controlState = processInstance.getControlState();
                            switch (controlState) {
                                case ProcessRuntimeConst.INST_STATE_ACTIVE:
                                    jsonObjectNew.put("processState", "审批中");
                                    processInst.add(processInstId);
                                    break;
                                case ProcessRuntimeConst.INST_STATE_CANCEL:
                                    jsonObjectNew.put("processState", "已取消");
                                    break;
                                case ProcessRuntimeConst.INST_STATE_END:
                                    jsonObjectNew.put("processState", "已完成");
                                    break;
                                case ProcessRuntimeConst.INST_STATE_SUSPEND:
                                    jsonObjectNew.put("processState", "已挂起");
                                    break;
                                case ProcessRuntimeConst.INST_STATE_TERMINATE:
                                    jsonObjectNew.put("processState", "已终止");
                                    break;
                                default:
                                    jsonObjectNew.put("processState", "状态异常");
                                    break;
                            }

                            List<RowMap> newMaps = maps.stream().filter(rowMap -> processInstId.equals(rowMap.getString("PROCESSINSTID"))).collect(Collectors.toList());
                            String targetUser = "";
                            String targetUserId = "";
                            String taskTimeInfo = "";
                            String createTime = jsonObject.getString("createTime");
                            String endTime = jsonObject.getString("endTime");
                            if (StringUtil.isNotEmpty(endTime)) {
                                try {

                                    taskTimeInfo = getTime(new Timestamp(simpleDateFormat1.parse(createTime.split("\\|")[0]).getTime()), new Timestamp(simpleDateFormat1.parse(endTime.split("\\|")[0]).getTime()), "总耗时") + ";";
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }

                            }


                            if (newMaps != null && newMaps.size() > 0) {
                                for (RowMap rowMap : newMaps) {
                                    String taskInstId = rowMap.getString("ID");
                                    TaskInstance taskInstance = SDK.getTaskAPI().getInstanceById(taskInstId);
                                    //获取任务节点
                                    String activityDefId = taskInstance.getActivityDefId();
                                    UserTaskModel userTaskModel = SDK.getRepositoryAPI().getUserTaskModel(processDefinition.getId(), activityDefId);
                                    if (userTaskModel != null) {
                                        //处理人员
                                        String uid = taskInstance.getTarget();
                                        if (StringUtils.isNotEmpty(uid)) {
                                            UserModel userModel = SDK.getORGAPI().getUser(uid);
                                            if (userModel != null) {
                                                targetUser = targetUser + SDK.getORGAPI().getUser(uid).getUserName() + ",";
                                            } else {
                                                targetUser = targetUser + "人员已删除" + ",";
                                            }
                                            targetUserId = targetUserId + uid + ",";
                                        } else {
                                            targetUser = targetUser + "未分配人,";
                                        }
                                        //处理超时信息
                                        //获取任务实例
                                        Timestamp beginTime = taskInstance.getBeginTime();
                                        //获取超时时间
                                        Timestamp dueTime = taskInstance.getDueTime();
                                        if (dueTime == null) {
                                            //不会超期，显示停留时间
                                            taskTimeInfo = taskTimeInfo + "【" + userTaskModel.getName() + "】" + getTime(beginTime, nowTime, "已停留") + ";";
                                        } else {
                                            if (nowTime.getTime() > dueTime.getTime()) {
                                                //超期
                                                taskTimeInfo = taskTimeInfo + "【" + userTaskModel.getName() + "】" + getTime(beginTime, nowTime, "已逾期") + ";";
                                            } else {
                                                taskTimeInfo = taskTimeInfo + "【" + userTaskModel.getName() + "】" + getTime(beginTime, nowTime, "已停留") + ";";
                                            }
                                        }
                                    }
                                }
                            }
                            jsonObjectNew.put("dataInfo", taskTimeInfo);
                            if (StringUtils.isNotEmpty(targetUser)) {
                                targetUser = targetUser.substring(0, targetUser.length() - 1);
                            }
                            if (StringUtils.isNotEmpty(targetUserId)) {
                                targetUserId = targetUserId.substring(0, targetUserId.length() - 1);
                            }
                            jsonObjectNew.put("targetUser", targetUser);
                            jsonObjectNew.put("targetUserId", targetUserId);
                            jsonObjectNew.put("isCanCB", StringUtil.isNotEmpty(targetUserId) ? true : false);
                            jsonArrayResult.add(jsonObjectNew);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    try {
                        conn.close();
                    } catch (SQLException throwables) {
                        throwables.printStackTrace();
                    }
                }
            }
        }
        return jsonArrayResult;
    }


    /**
     * 待办任务数量
     *
     * @return
     */
    public ResponseObject getTodoNum(UserContext userContext) {
        // 调用App
        String sourceAppId = "com.actionsoft.apps.workbench";
        // aslp服务地址
        String aslp = "aslp://com.actionsoft.apps.workbench/TodoTaskCountByUserASLP";
        // 参数定义列表
        Map params = new HashMap<String, Object>();
        //sessionId,必填
        params.put("sid", userContext.getSessionId());
        AppAPI appAPI = SDK.getAppAPI();
        //待办任务数量
        ResponseObject ro = appAPI.callASLP(appAPI.getAppContext(sourceAppId), aslp, params);
        return ro;
    }


    /**
     * 获取常用流程
     *
     * @param userContext
     * @return
     */
    public ResponseObject getCommonProcessList(UserContext userContext) {
        // 调用App
        String sourceAppId = "com.actionsoft.apps.workbench";
        // aslp服务地址
        String aslp = "aslp://com.actionsoft.apps.workbench/CommonProcessListByUserIdASLP";
        // 参数定义列表
        Map params = new HashMap<String, Object>();
        //sessionId,必填
        params.put("sid", userContext.getSessionId());
        AppAPI appAPI = SDK.getAppAPI();
        //常用流程列表
        ResponseObject ro = appAPI.callASLP(appAPI.getAppContext(sourceAppId), aslp, params);
        return ro;
    }

    /**
     * 添加常用流程
     *
     * @param userContext
     * @return
     */
    public ResponseObject setCommonProcessList(UserContext userContext, JSONObject processData) {
        // 调用App
        String sourceAppId = "com.actionsoft.apps.workbench";
        // aslp服务地址
        String aslp = "aslp://com.actionsoft.apps.workbench/AddCommonProcessASLP";
        // 参数定义列表
        Map params = new HashMap<String, Object>();
        //jsonobject结构流程信息，包括processDefId、processName、icon信息,必填
        params.put("processData", processData);
        //sessionId,必填
        params.put("sid", userContext.getSessionId());
        AppAPI appAPI = SDK.getAppAPI();
        //添加常用流程
        ResponseObject ro = appAPI.callASLP(appAPI.getAppContext(sourceAppId), aslp, params);
        return ro;
    }

    /**
     * 删除常用流程
     *
     * @param userContext
     * @return
     */
    public ResponseObject removeCommonProcessList(UserContext userContext, JSONObject processData) {
        // 调用App
        String sourceAppId = "com.actionsoft.apps.workbench";
        // aslp服务地址
        String aslp = "aslp://com.actionsoft.apps.workbench/RemoveCommonProcessASLP";
// 参数定义列表
        Map params = new HashMap<String, Object>();
//jsonobject结构流程信息，包括processDefId、processName、icon信息,必填
        params.put("processData", processData);
//sessionId,必填
        params.put("sid", userContext.getSessionId());
        AppAPI appAPI = SDK.getAppAPI();
//移除常用流程
        ResponseObject ro = appAPI.callASLP(appAPI.getAppContext(sourceAppId), aslp, params);
        return ro;
    }


    public boolean getAc(List<PermissionAssnModel> userPermissionAssnList, List<PermissionAssnModel> deptPermissionAssnList, List<PermissionAssnModel> rolePermissionAssnList, List<UserMapModel> mapRoles, String resourceId, Query1Model q1Model, UserModel currentUserModel) {
        for (int i = 0; i < userPermissionAssnList.size(); i++) {
            PermissionAssnModel permissionAssnModel = (PermissionAssnModel) userPermissionAssnList.get(i);
            if (this.isPermissionHasResource(permissionAssnModel.getPermissionId(), resourceId)) {
                return true;
            }
        }

        for (int i = 0; i < deptPermissionAssnList.size(); i++) {
            PermissionAssnModel permissionAssnModel = (PermissionAssnModel) deptPermissionAssnList.get(i);
            if (this.isPermissionHasResource(permissionAssnModel.getPermissionId(), resourceId)) {
                return true;
            }
        }

        for (int i = 0; i < rolePermissionAssnList.size(); i++) {
            PermissionAssnModel permissionAssnModel = (PermissionAssnModel) rolePermissionAssnList.get(i);
            if (this.isPermissionHasResource(permissionAssnModel.getPermissionId(), resourceId)) {
                return true;
            }
        }
        for (int i = 0; i < mapRoles.size(); i++) {
            UserMapModel mapModel = (UserMapModel) mapRoles.get(i);
            rolePermissionAssnList = q1Model.getRolePermissionAssnListByRoleId(mapModel.getRoleId());

            for (int j = 0; j < rolePermissionAssnList.size(); j++) {
                PermissionAssnModel permissionAssnModel = (PermissionAssnModel) rolePermissionAssnList.get(j);
                if (this.isPermissionHasResource(permissionAssnModel.getPermissionId(), resourceId)) {
                    return true;
                }
            }
            deptPermissionAssnList = q1Model.getDeptPermissionAssnListByDeptId(mapModel.getDepartmentId());
            for (int z = 0; z < deptPermissionAssnList.size(); z++) {
                PermissionAssnModel permissionAssnModel = (PermissionAssnModel) deptPermissionAssnList.get(i);
                if (this.isPermissionHasResource(permissionAssnModel.getPermissionId(), resourceId)) {
                    return true;
                }
            }
        }

        List<PermissionAssnModel> orgrolePermissionAssnList = q1Model.getOrgrolePermissionAssnList(currentUserModel);
        Iterator var21 = orgrolePermissionAssnList.iterator();
        PermissionAssnModel permissionAssnModel;
        do {
            if (!var21.hasNext()) {
                boolean isAc = AccessControlAPI.getInstance().havingPermission(currentUserModel.getUID(), q1Model.getACList(NavFunctionACCM.resourceType, resourceId).iterator(), NavFunctionACCM.VISIT.getType());
                return isAc;
            }
            permissionAssnModel = (PermissionAssnModel) var21.next();
        } while (!this.isPermissionHasResource(permissionAssnModel.getPermissionId(), resourceId));
        return true;
    }

    private final boolean isPermissionHasResource(String permissionId, String resourceId) {
        Iterator it = PermissionListCache.getListOfPermission(permissionId);

        PermissionListModel model;
        do {
            if (!it.hasNext()) {
                return false;
            }

            model = (PermissionListModel) it.next();
        } while (!model.getResourceId().equals(resourceId));

        return true;
    }
}
